package com.gewu.pm.ui.adapter.home;

import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;

import com.gewu.pm.R;
import com.gewu.pm.bean.ClockInStatisticsBean;
import com.gewu.pm.app.AppAdapter;

import java.util.ArrayList;
import java.util.List;

/**
 * 可展开的打卡列表适配器
 * 参考SelectSubmitterDialog的DepartmentAdapter，但少一个层级
 */
public class ExpandableClockInAdapter extends AppAdapter<Object> {

    private static final int TYPE_GROUP = 0;    // 分组类型
    private static final int TYPE_EMPLOYEE = 1; // 员工类型

    private final List<Object> mAllItems = new ArrayList<>();
    private final List<Object> mDisplayItems = new ArrayList<>();
    private OnDataChangeListener mDataChangeListener;

    public ExpandableClockInAdapter(Context context) {
        super(context);
    }

    /**
     * 设置打卡统计数据
     * 
     * 作用：将业务数据转换为可展开列表的UI数据结构
     * 调用时机：每次数据变化时（如切换日期、刷新数据）
     * 
     * 处理逻辑：
     * 1. 根据统计数据创建分组项（迟到、早退、旷工）
     * 2. 将员工列表添加到对应分组下
     * 3. 初始状态只显示分组标题，不展开员工列表
     * 4. 用户点击分组时可展开/收起员工列表
     */
    public void setClockInData(ClockInStatisticsBean statistics) {
        mAllItems.clear();
        mDisplayItems.clear();

        if (statistics == null) {
            notifyDataSetChanged();
            return;
        }

        // 添加迟到分组和员工
        if (statistics.getLateCount() > 0) {
            GroupItem lateGroup = new GroupItem("迟到", statistics.getLateCount(), false);
            mAllItems.add(lateGroup);
            mDisplayItems.add(lateGroup); // 初始只显示分组标题
            if (statistics.getLateList() != null) {
                mAllItems.addAll(statistics.getLateList()); // 员工数据存储在mAllItems中，点击时展开
            }
        }

        // 添加早退分组和员工
        if (statistics.getEarlyLeaveCount() > 0) {
            GroupItem earlyLeaveGroup = new GroupItem("早退", statistics.getEarlyLeaveCount(), false);
            mAllItems.add(earlyLeaveGroup);
            mDisplayItems.add(earlyLeaveGroup); // 初始只显示分组标题
            if (statistics.getEarlyLeaveList() != null) {
                mAllItems.addAll(statistics.getEarlyLeaveList()); // 员工数据存储在mAllItems中，点击时展开
            }
        }

        // 添加旷工分组和员工
        if (statistics.getAbsentCount() > 0) {
            GroupItem absentGroup = new GroupItem("旷工", statistics.getAbsentCount(), false);
            mAllItems.add(absentGroup);
            mDisplayItems.add(absentGroup); // 初始只显示分组标题
            if (statistics.getAbsentList() != null) {
                mAllItems.addAll(statistics.getAbsentList()); // 员工数据存储在mAllItems中，点击时展开
            }
        }

        // 通知RecyclerView更新显示
        setData(mDisplayItems);
    }


    @Override
    public int getItemViewType(int position) {
        Object item = getItem(position);
        if (item instanceof GroupItem) {
            return TYPE_GROUP;
        } else {
            return TYPE_EMPLOYEE;
        }
    }

    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        if (viewType == TYPE_GROUP) {
            return new GroupViewHolder();
        } else {
            return new EmployeeViewHolder();
        }
    }

    /**
     * 分组ViewHolder
     */
    private final class GroupViewHolder extends AppAdapter<Object>.ViewHolder {

        private final TextView mGroupTitle;
        private final ImageView mExpandArrow;

        private GroupViewHolder() {
            super(R.layout.clock_in_group_item);
            mGroupTitle = findViewById(R.id.tv_group_title);
            mExpandArrow = findViewById(R.id.iv_expand_arrow);
        }

        @Override
        public void onBindView(int position) {
            GroupItem groupItem = (GroupItem) getItem(position);
            
            mGroupTitle.setText(groupItem.getTitle() + " (" + groupItem.getCount() + ")");
            
            // 设置箭头方向
            if (groupItem.isExpanded()) {
                mExpandArrow.setImageResource(R.drawable.arrow_shang);
            } else {
                mExpandArrow.setImageResource(R.drawable.arrow_xia);
            }

            // 点击展开/收起
            itemView.setOnClickListener(v -> {
                toggleGroup(position);
            });
        }
    }

    /**
     * 员工ViewHolder
     */
    private final class EmployeeViewHolder extends AppAdapter<Object>.ViewHolder {

        private final ImageView mEmployeeAvatar;
        private final TextView mEmployeeName;

        private EmployeeViewHolder() {
            super(R.layout.clock_in_employee_item);
            mEmployeeAvatar = findViewById(R.id.iv_employee_avatar);
            mEmployeeName = findViewById(R.id.tv_employee_name);
        }

        @Override
        public void onBindView(int position) {
            ClockInStatisticsBean.EmployeeClockInBean employee = 
                (ClockInStatisticsBean.EmployeeClockInBean) getItem(position);
            
            mEmployeeName.setText(employee.getEmployeeName());
            
            // 可以根据需要设置不同的头像
            mEmployeeAvatar.setImageResource(R.drawable.head_placeholder);
        }
    }

    /**
     * 切换分组展开/收起状态
     */
    private void toggleGroup(int groupPosition) {
        GroupItem groupItem = (GroupItem) getItem(groupPosition);
        groupItem.setExpanded(!groupItem.isExpanded());

        // 重新构建显示列表
        rebuildDisplayList();
        
        // 通知数据变化回调
        if (mDataChangeListener != null) {
            mDataChangeListener.onDataChanged();
        }
    }

    /**
     * 重新构建显示列表
     */
    private void rebuildDisplayList() {
        mDisplayItems.clear();
        
        GroupItem currentGroup = null;
        for (Object item : mAllItems) {
            if (item instanceof GroupItem) {
                currentGroup = (GroupItem) item;
                mDisplayItems.add(item);
            } else if (currentGroup != null && currentGroup.isExpanded()) {
                mDisplayItems.add(item);
            }
        }
        
        setData(mDisplayItems);
    }

    /**
     * 分组数据类
     */
    public static class GroupItem {
        private String title;
        private int count;
        private boolean expanded;

        public GroupItem(String title, int count, boolean expanded) {
            this.title = title;
            this.count = count;
            this.expanded = expanded;
        }

        public String getTitle() {
            return title;
        }

        public void setTitle(String title) {
            this.title = title;
        }

        public int getCount() {
            return count;
        }

        public void setCount(int count) {
            this.count = count;
        }

        public boolean isExpanded() {
            return expanded;
        }

        public void setExpanded(boolean expanded) {
            this.expanded = expanded;
        }
    }

    /**
     * 数据变化监听器
     */
    public interface OnDataChangeListener {
        void onDataChanged();
    }

    public void setOnDataChangeListener(OnDataChangeListener listener) {
        this.mDataChangeListener = listener;
    }
}
